<template>
  <q-select
      filled
      v-model="tagValue"
      use-input
      use-chips
      input-debounce="0"
      label="标签选择"
      :options="tagOptions"
      :option-value="opt=>opt? opt._id : null"
      :option-label="opt=>opt? opt.name : null"
      emit-value
      map-options
      @filter="filterFn"
      @input="handleTagSelectChange"
      style="width: 200px"
      size="sm"
      dense
  >
    <template v-slot:prepend>
      <q-icon name="label"/>
    </template>
    <template v-slot:no-option>
      <q-item>
        <q-item-section class="text-grey">
          无匹配标签
        </q-item-section>
      </q-item>
    </template>
  </q-select>
</template>

<script>

import iToolTag from 'src/api/toolTag'

export default {
  name: 'ToolTagSelect',
  props: {
    filterTags: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      tagValue: null,
      tagSelectLoading: false,
      tagOptions: []
    }
  },
  async mounted () {
    this.tagList = await iToolTag.findAll()
  },
  methods: {
    filterTagOptions (query) {
      this.tagOptions = this.tagList.filter(item => {
        // 过滤已选中标签
        const matchSelectTag = this.filterTags.find(e => e._id === item._id)
        let matchQuery = true
        if (query) {
          matchQuery = item.name.toLowerCase().indexOf(query.toLowerCase()) > -1
        }
        return matchQuery && !matchSelectTag
      })
      return this.tagOptions
    },
    handleTagSelectChange (selectId) {
      const selectTag = this.tagList.find(e => e._id === selectId)
      this.tagValue = null
      this.filterTagOptions()
      this.$emit('change', selectTag)
    },
    filterFn (val, update) {
      update(() => {
        this.tagOptions = this.filterTagOptions(val)
      })
    }
  }
}
</script>

<style scoped>

</style>
